package com.hotel.front;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.FixedPackageLogic;
import com.hotel.BL.GenericLogic;
import com.hotel.BL.GuestTypeLogic;
import com.hotel.BL.PackagePriceLogic;
import com.hotel.BL.PopupLogic;
import com.hotel.BL.RoomTypeLogic;

import data.FixedPackage;
import data.PackagePrice;
import data.passingData.FixPackageData;
import data.passingData.FixedPackageData;
import data.passingData.PackagePriceData;
import data.passingData.ResultData;

@SuppressWarnings("serial")
public class FixedPackageService extends HttpServlet{
	//http://localhost:8080/fixedpackageservice?func=addfixedpackage
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			String doClass = req.getParameter("func");
			if(doClass.equals("getfixpagedata")){
				GetFixedPageData(req,resp);
			}else if(doClass.equals("addfixedpackage")){
				AddFixedPackage(req,resp);
			}else if(doClass.equals("getallfixedpackage")){
				GetAllFixedPackage(req,resp);
			}else if(doClass.equals("changeFixedPackage")){
				ChangeStatus(req, resp);
			}else if(doClass.equals("delFixedPackage")){
				DeleteFixedPackage(req, resp);
			}else if(doClass.equals("getpackagetimebyid")){
				GetPackageTimeById(req, resp);
			}else if(doClass.equals("editpackagetime")){
				EditPackageTime(req, resp);
			}else if(doClass.equals("changestatustime")){
				ChangeStatusTimes(req, resp);
			}else if(doClass.equals("changeArchived")){
				ChangeArchived(req, resp);
			}else if(doClass.equals("getallarchivedfixedpackage")){
				GetAllArchivedFixedPackage(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void GetFixedPageData(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{		
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		long id = 0;
		if(req.getParameter("id")!=null){
			id = Long.parseLong(req.getParameter("id"));
		}
		
		FixPackageData fixdata = new FixPackageData();
		fixdata.setDateFormatString(new GenericLogic(req,resp).GetGeneral(hotelId).getDateFormat().getDateTimeFormat());
		fixdata.setGuesttype(new GuestTypeLogic().GetAllGuestType(hotelId));
		fixdata.setRoomtype(new RoomTypeLogic(req,resp).GetAllRoomType(hotelId));
		FixedPackageData fpData = new FixedPackageData();
		if(id != 0){
			fpData = new FixedPackageLogic().GetFixedPackageDataById(id);
		}else{
			fpData =  null;
		}
		
		List<Object> obj = new ArrayList<Object>();
		obj.add(fixdata);
		obj.add(fpData);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void AddFixedPackage(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException, ParseException
	{		
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		String id = req.getParameter("id");
		String packagename = req.getParameter("packagename");
		long longofstay = Long.parseLong(req.getParameter("longofstay"));
		String description = req.getParameter("description");
		boolean isforever = Boolean.parseBoolean(req.getParameter("isforever"));
		
		Date from = new Date();
		Date to = new Date();
		if(req.getParameter("from") != null || req.getParameter("to") != null){
			from = formatter.parse(req.getParameter("from"));
			to = formatter.parse(req.getParameter("to"));
		}
		
		String guesttype = req.getParameter("guesttype");
		boolean status = Boolean.parseBoolean(req.getParameter("status"));
		Date ServerDate = new GenericLogic(req,resp).ServerDateTime(hotelId);
		String pricedata = req.getParameter("pricedata");
		String [] a =pricedata.split("-");
		String packagepricestring = "";
		for(int i=0;i<a.length;i++){
			String[] ss = a[i].split(",");
			String roomtypeid = ss[0];
			double ppn = Double.parseDouble(ss[1]);
			double upp = Double.parseDouble(ss[2]);
			double exbed = Double.parseDouble(ss[3]);
			PackagePrice price = new PackagePriceLogic(req,resp).AddPackagePrice(hotelId, exbed, 
					upp, ppn, roomtypeid);
			packagepricestring += price.getId() + ",";
		}
		packagepricestring.substring(0, packagepricestring.length()-1);
		FixedPackage obj;
		if(id == null){
			obj = new FixedPackageLogic().AddFixedPackage(hotelId, guesttype,
					status, description, isforever, from, to, longofstay, packagename, packagepricestring,ServerDate);
		}else{
			obj = new FixedPackageLogic().EditFixedPackage(Long.parseLong(id), guesttype,
					status, description, isforever, from, to, longofstay, packagename, packagepricestring,ServerDate);
		}
		if(obj.isArchive())
			GetAllArchivedFixedPackage(req,resp);
		else
			GetAllFixedPackage(req,resp);
		
	}
	
	private void GetAllFixedPackage(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		long offset = Long.parseLong(req.getParameter("offset"));
		long line = Long.parseLong(req.getParameter("line"));
		long pointer = Long.parseLong(req.getParameter("pagePointer"));
		List<FixedPackage> obj = new FixedPackageLogic().GetAllFixedPackage4AdminLimit(hotelId,offset,line);
		List<FixedPackageData> fixdatalist = new ArrayList<FixedPackageData>();
		for(int i =0;i<obj.size();i++){
			FixedPackageData fixdata = new FixedPackageData();
			fixdata.setPackagename(obj.get(i).getPackageName());
			List<PackagePriceData> ppdList = new ArrayList<PackagePriceData>();
			
			for(int y=0;y< obj.get(i).getPackagepriceList().size();y++){
				PackagePriceData ppd = new PackagePriceData();
				ppd.setPriceperNight(obj.get(i).getPackagepriceList().get(y).getPriceperNight());
				ppd.setRoomtypeName(obj.get(i).getPackagepriceList().get(y).getRoomtype().getShortName());
				ppdList.add(ppd);
			}
			
			fixdata.setPackageprice(ppdList);
			fixdata.setForever(obj.get(i).isForever());
			fixdata.setStatus(obj.get(i).isStatus());
			if(!obj.get(i).isStatus()){
				fixdata.setFrom(obj.get(i).getFrom());
				fixdata.setTo(obj.get(i).getTo());
			}
			fixdatalist.add(fixdata);
		}
		double dataSize = new FixedPackageLogic().GetAllFixedPackage4Admin(hotelId).size();
		double dataSizeArchived = new FixedPackageLogic().GetAllArchivedFixedPackage4Admin(hotelId).size();
		String dateformat = new PopupLogic(req,resp).LoadGeneral(hotelId).getDateFormat().getDateTimeFormat();
		List<Object> rsObj = Arrays.asList(dataSize,pointer,line,obj,dateformat,dataSizeArchived);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsObj));
	}
	
	private void GetAllArchivedFixedPackage(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		long offset = Long.parseLong(req.getParameter("offset"));
		long line = Long.parseLong(req.getParameter("line"));
		long pointer = Long.parseLong(req.getParameter("pagePointer"));
		List<FixedPackage> obj = new FixedPackageLogic().GetAllArchivedFixedPackage4AdminLimit(hotelId,offset,line);
		List<FixedPackageData> fixdatalist = new ArrayList<FixedPackageData>();
		for(int i =0;i<obj.size();i++){
			FixedPackageData fixdata = new FixedPackageData();
			fixdata.setPackagename(obj.get(i).getPackageName());
			List<PackagePriceData> ppdList = new ArrayList<PackagePriceData>();
			
			for(int y=0;y< obj.get(i).getPackagepriceList().size();y++){
				PackagePriceData ppd = new PackagePriceData();
				ppd.setPriceperNight(obj.get(i).getPackagepriceList().get(y).getPriceperNight());
				ppd.setRoomtypeName(obj.get(i).getPackagepriceList().get(y).getRoomtype().getShortName());
				ppdList.add(ppd);
			}
			
			fixdata.setPackageprice(ppdList);
			fixdata.setForever(obj.get(i).isForever());
			fixdata.setStatus(obj.get(i).isStatus());
			if(!obj.get(i).isStatus()){
				fixdata.setFrom(obj.get(i).getFrom());
				fixdata.setTo(obj.get(i).getTo());
			}
			fixdatalist.add(fixdata);
		}
		double dataSize = new FixedPackageLogic().GetAllFixedPackage4Admin(hotelId).size();
		double dataSizeArchived = new FixedPackageLogic().GetAllArchivedFixedPackage4Admin(hotelId).size();
		String dateformat = new PopupLogic(req,resp).LoadGeneral(hotelId).getDateFormat().getDateTimeFormat();
		List<Object> rsObj = Arrays.asList(dataSizeArchived,pointer,line,obj,dateformat,dataSize);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsObj));
	}
	
	private void ChangeStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long id = Long.parseLong(req.getParameter("id"));
		FixedPackage obj = new FixedPackageLogic().ChangeStatus(id);
		 
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void DeleteFixedPackage(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String idList = req.getParameter("id");
		for(int i = 0; i < idList.split(",").length ; i++){
			new FixedPackageLogic().DeleteFixedPackage(Long.parseLong(idList.split(",")[i]));
		}
		
		GetAllFixedPackage(req,resp);
	}
	
	private void GetPackageTimeById(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long id = Long.parseLong(req.getParameter("id"));
		FixedPackage fpData =  new FixedPackageLogic().GetFixedPackage(id);

		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(fpData));
	}
	
	private void EditPackageTime(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException, ParseException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		long id = Long.parseLong(req.getParameter("id"));
		boolean isforever = Boolean.parseBoolean(req.getParameter("isforever"));
		FixedPackage fixedpackage = new FixedPackageLogic().GetFixedPackage(id);
		fixedpackage.setForever(isforever);
		if(!isforever){
			Date datefrom = formatter.parse(req.getParameter("datefrom"));
			Date dateto = formatter.parse(req.getParameter("dateto"));
			fixedpackage.setFrom(datefrom);
			fixedpackage.setTo(dateto);
		}
		new FixedPackageLogic().UpdateFixedPackage(fixedpackage);

		GetAllFixedPackage(req,resp);
	}
	
	private void ChangeStatusTimes(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException, ParseException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		long id = Long.parseLong(req.getParameter("id"));
		boolean isforever = Boolean.parseBoolean(req.getParameter("isforever"));
		FixedPackage fixedpackage = new FixedPackageLogic().GetFixedPackage(id);
		fixedpackage.setForever(isforever);
		if(!isforever){
			Date datefrom = formatter.parse(req.getParameter("datefrom"));
			Date dateto = formatter.parse(req.getParameter("dateto"));
			fixedpackage.setFrom(datefrom);
			fixedpackage.setTo(dateto);
		}
		new FixedPackageLogic().UpdateFixedPackage(fixedpackage);
		new FixedPackageLogic().ChangeStatus(id);
		
		GetAllFixedPackage(req,resp);
	}
	
	private void ChangeArchived(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String idList = req.getParameter("id");
		FixedPackage obj = null;
		for(int i = 0; i < idList.split(",").length ; i++){
			obj = new FixedPackageLogic().ChangeArchivedLogic(Long.parseLong(idList.split(",")[i]));
		}
		
		if(obj!=null){
			if(obj.isArchive())
				GetAllFixedPackage(req,resp);
			else
				GetAllArchivedFixedPackage(req,resp);
		}else{
			GetAllFixedPackage(req,resp);
		}
		
	}
}
